<?php
// 这是系统自动生成的公共文件

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

//生成验签
function signToken($uid, $key, $expire): string
{
    $token = array(
        "iss" => $key,              //签发者 可以为空
        "aud" => '',                //面象的用户，可以为空
        "iat" => time(),            //签发时间
        "nbf" => time(),            //在什么时候jwt开始生效
        "exp" => time() + $expire,  //token 过期时间
        "data" => [
            'uid' => $uid,
        ]
    );
    //根据参数生成了 token
    return JWT::encode($token, $key, "HS256");
}

//验证token
function checkToken($token, $key)
{
    try {
        JWT::$leeway = 60;//当前时间减去60，把时间留点余地
        $decoded = JWT::decode($token, new Key($key, 'HS256'));
        $arr = (array)$decoded;
        $res['status'] = 200;
        $res['data'] = $arr['data'];
        return $res;
    } catch (SignatureInvalidException $e) {
        return "签名不正确";
    } catch (BeforeValidException | ExpiredException $e) {
        return "token失效";
    } catch (Exception $e) {
        return "未知错误";
    }
}

/**
 * 格式化权限列表
 * @param $data
 * @param int $pid
 * @return array
 */
function formatAuth($data, int $pid = 0): array
{
    $authList = array();
    foreach ($data as $k => $v) {
        if ($v['pid'] == $pid) {
            $v['children'] = formatAuth($data, $v['id']);
            $authList[] = $v;
            unset($data[$k]);
        }
    }
    return $authList;
}